<?php
use Illuminate\Support\Facades\Response as FacadesResponse;
use \Illuminate\Database\Eloquent\ModelNotFoundException;

/**
 * @author gaozongwei
 */
class MicroblogController extends CenterController {
	

	protected function getStubMicroblogs()
	{
        $data = [];
        $data[] = [
        	'id' => 1,
        	'content' => "test 1",							// 动态内容
        	'comments_count' => 3,						// 评论数
        	'likes_count' => 3,							// 点赞数
        	'created_at' => '2015-10-29 09:51:19',
        	'updated_at' => '2015-10-30 09:51:19'
        ];
        $data[] = [
        	'id' => 2,
        	'content' => "test 2",							// 动态内容
        	'comments_count' => 4,						// 评论数
        	'likes_count' => 4,							// 点赞数
        	'created_at' => '2015-11-01 09:51:19',
        	'updated_at' => '2015-11-02 09:51:19'
        ];
        $data[] = [
        	'id' => 3,
        	'content' => "test 3",							// 动态内容
        	'comments_count' => 5,						// 评论数
        	'likes_count' => 5,							// 点赞数
        	'created_at' => '2015-11-03 09:51:19',
        	'updated_at' => '2015-11-04 09:51:19'
        ];
        $data[] = [
        	'id' => 4,
        	'content' => "test 4",							// 动态内容
        	'comments_count' => 6,						// 评论数
        	'likes_count' => 6,							// 点赞数
        	'created_at' => '2015-11-05 09:51:19',
        	'updated_at' => '2015-11-06 09:51:19'
        ];
        return $data;
	}


	/**
	 * 发布动态
	 */
	public function create() {
		if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
			$post = Input::all();		
			$rules = array (
					'content' => 'required|between:0,140'					
			);
			$messages = array(
					'content.required' => '请填写内容',
					'content.between' => '内容长度在:min到:max之间',
			);
				
			$validator = Validator::make ( $post, $rules, $messages );
			if ($validator->fails()) {
				return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
					);
			}
			// 验证成功
			try {
					$new_post = Post::storeMicroblog($post);
			} catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'发表失败，请稍后再试',
						503
					);
			}
				
			return $this->makeView(
					'general.201',
					['id' => $new_post->id],
					201	
				);
			} else {
				$this->makeView( 'microblog.create' );
			}	
	
	}

	/**
	 * 分享动态
	 */
	public function forward() {
			$post = Input::all();
			Validator::extend('duplicate', function() use($post){
				$result = Post::where('creator_id', Auth::user()->id)->where('parent_id', $post['parent_id'])->count();
				return !(bool)$result;
			});
			$rules = array (
					'content' => 'between:0,140',
					'parent_id' => 'required|duplicate|exists:posts,id'					
			);
			$messages = array(
					'content.between' => '内容长度在:min到:max之间',
					'parent_id.required' => '请提交原文id',
					'parent_id.duplicate' => '你已经转发过该广播',
					'parent_id.exists' => '该广播不存在'
			);
				
			$validator = Validator::make ( $post, $rules, $messages );
			if ($validator->fails()) {
				return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
					);
			}
			// 验证成功
			try {
					$new_post = Post::storeMicroblog($post);
			} catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView('errors.503', '发表失败，请稍后再试', 503);
			}
			return $this->makeView('general.201', ['id' => $new_post->id], 201);	
	}
	
	/*
	 * 
	 */
	public function view($id){
		$post = Post::select('id', 'creator_id', 'content', 'created_at', 'parent_id')->find($id);
		if(empty($post)){
			return $this->makeView(
					'errors.404',
					'该动态不存在',
					404
			);
		}
		$post->load('postExtra');
        $post->user = $post->getUserinfo();
        $post->comments = $post->getComments();
        $post->postAttach = $post->getAttach();
		$post->likeUser = Like::getCreateLikeUser($post->id);
		return $this->makeView('microblog.view',$post->toArray(),200);
	}
	
	/*
	 * 删除动态
	 */
	public function delete($id) {
		$post = Post::find($id);
		if(empty($post)){
			return $this->makeView(
						'errors.404',
						'该动态不存在',
						404
					);
		}
		if($post->creator_id != Auth::user()->id){
			return $this->makeView(
						'errors.401',
						'您没有权限删除该动态',
						401
					);
		}
		try{
			$post->delete();
		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503',
				'删除失败,请重试',
				503	
			);
		}
		return $this->makeView(
				'general.200',
				'删除成功',
				200	
			);
	}
	/*
	 * 评论
	 */
	public function createComment() {
		if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
			$post = Input::all();
				
			$rules = array (
					'content' => 'required|between:0,140',
					'post_id' => 'required|exists:posts,id'
						
			);
			$messages = array(
					'content.required' => '请填写内容',
					'content.between' => '内容长度在:min到:max之间',
					'post_id.required' =>'请选择您要评论的动态',
					'post_id.exists' => '您要评论的动态不存在'
			);	
			$validator = Validator::make ( $post, $rules, $messages );
			if ($validator->fails()) {
				return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
					);
			}
			// 验证成功
			try {

					$new_post = Comment::createComment($post);
					$new_post->user_name = $new_post->creatorName();
			} catch (Exception $ex) {
				Log::error($ex);
					return $this->makeView(
						'errors.503',
						'服务器暂时没有响应，请稍后再试',
						503	
					);
			}
			return $this->makeView('general.201', $new_post->toArray(),201);

		} 
	}
	
	/**
	 * 查看我的动态
	 */
	public function microBlogListMine() {
// 		$postArr = $this->getStubMicroblogs();
// 		return $this->makeView('microblog.list', $postArr);

		$input = Input::all();
		$page = Input::get('page', 1);
		$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = ($page-1) * $rows_per_page;
		$orderby = 'created_at';
		$direction = 'DESC';
		$rules = array (
				
				'page' => 'numeric|min:1',
				'rows_per_page' => 'numeric|min:1'
				
		);
		$messages = array(				
				'page.numeric' => 'page需要是数字',
				'rows_per_page.numeric' => 'rows_per_page需要是数字',
		);
		$validator = Validator::make ( $input, $rules, $messages );
		if ($validator->fails()) {
			return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
					);
		}
		try{
			$posts = Post::getMicroblogPosts(
					$offset,
					$rows_per_page,
					$orderby,
					$this->user->id
			);
			//
			$posts = Post::getParentPost($posts);			

			$posts->load('postExtra');
			foreach($posts as $post){
				$post->user = $post->getUserinfo();
				$post->comments = $post->getComments();
				$post->postAttach = $post->getAttach();
				$post->likeUser = Like::getCreateLikeUser($post->id);
			}

			} catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'获取动态内容失败，请重试',
						503
				);
			}	
			return $this->makeView('microblog.list', $posts->toArray() );
	}

	public function microBlogListAll(){
// 		$postArr = $this->getStubMicroblogs();
// 		return $this->makeView('microblog.list', $postArr);
		$input = Input::all();
		$page = Input::get('page', 1);
		$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);

		$offset = ($page-1) * $rows_per_page;
		$orderby = 'created_at';
		$direction = 'DESC';
		$rules = array (
		
				'page' => 'numeric|min:1',
				'rows_per_page' => 'numeric|min:1'
		
		);
		$messages = array(
				'page.numeric' => 'page需要是数字',
				'rows_per_page.numeric' => 'rows_per_page需要是数字',
		);
		$validator = Validator::make ( $input, $rules, $messages );
		if ($validator->fails()) {
			return $this->makeView(
						'errors.400',
						$validator->errors(),
						400
					);
		}		
		try{			
			$follow_id = DB::table('follows')->select('follow_id')->where('user_id',$this->user->id)->where('follow_stat',1)->get();
			$follow=array();
			foreach($follow_id as $rows){				
				$follow[] = $rows->follow_id;
			}
			$follow[count($follow)] = Auth::user()->id;
			$posts = Post::getFollowMicroblogPosts($offset, $rows_per_page,$orderby,$follow);
			$posts = Post::getParentPost($posts);
			$posts->load('postExtra');
			foreach($posts as $post){
				$post->user = $post->getUserinfo();
				$post->comments = $post->getComments();
				$post->postAttach = $post->getAttach();
				$post->likeUser = Like::getCreateLikeUser($post->id);
			}			
		}catch (Exception $ex) {
				Log::error($ex);
				return $this->makeView(
						'errors.503',
						'获取动态内容失败，请重试',
						503
				);
			}		
			return $this->makeView('microblog.list', $posts);
	}
	
	
	
	 
	/**
	 * ajax上传图片
	 * @param string $field_name
	 */
	public function uploadImage($imageIds=array(),$field_name='microBlogImage')
	{
		$type_arr=explode('.', $_FILES['microBlogImage']['name']);
		$type=end($type_arr);
		$allow_exts = ['jpg','jpeg','jpe','png','gif','bmp'];
		if(!in_array( strtolower($type), $allow_exts)){
			return $this->makeView(
					'errors.400',
					'图片格式不正确'	,
					400
			);
		}
		if (count($imageIds)>9) {
			return $this->makeView(
					'errors.400',
					'最多只能上传9张图片'	,
					400
				);
		}
		$upload_folder = Config::get('app.upload_dir').'/microblog_image/';
		try{
			$upload_result  = UploadHelper::uploadImage($field_name, $upload_folder);
			if ($upload_result['error'] == 0){
	
				for ($i=0; $i<count($upload_result['files']); $i++){
	
	
					$upload_result['files'][$i]['url'] = $upload_result['files'][$i]['path'];
					$postAttach =new PostAttach;
					$postAttach->post_id = '';
					$postAttach->src = $upload_result['files'][$i]['url'];
					$postAttach->src_url = UtilsHelper::getImage($upload_result['files'][$i]['url'],null);	
					
				}
			}
		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503',
				'服务器暂时没有响应，请稍后再试',
				503	
			);
		}
		return $this->makeView(
				'general.201',
				$postAttach->toArray(),
				201	
			);
	}	
}